<?php
include('config.inc.php');

if (isset($_GET['getUserId'])) {
	$url = $_GET['url'];
	eval('$userId = '.$config['userIdAlgorithm'].';');
	saveUserInDB($userId, $url);
	echo $userId;
	exit();
}

if (!isset($_GET['userId'])) {
	die("ERROR:Missing userId.");
}

if (isset($_GET['addPageToProfile'])) {
	$userId = urlencode($_GET['userId']);
	$pageUrl = urlencode($_GET['url']);
	$url = "https://profiler.engagd.com/user/".$config['devKey']."/$userId/pages?url=$pageUrl";
	echo apml_request($url, 'PUT');
	exit();
}
if (isset($_GET['getProfile'])) {
	$userId = urlencode($_GET['userId']);
	$url = "https://apml.engagd.com/user/".$config['devKey']."/$userId/apml";
	echo apml_request($url);
	exit();
}

// Functions //
function saveUserInDB($userId, $url) {
	global $config;
	$link = mysql_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_password'])
		or die("ERROR:Could not connect: " . mysql_error() . "\n");
	mysql_select_db($config['mysql_db_name'], $link)
		or die ("ERROR:Can't use ".$config['mysql_db_name']." database: " . mysql_error() . "\n");

	mysql_query("CREATE TABLE IF NOT EXISTS engagd_users (userId TEXT NOT NULL, url TEXT NOT NULL, PRIMARY KEY (userId(50))) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci")
		or die("ERROR:Failed CREATE engagd_users TABLE: " . mysql_error() . "\n");

	$query = sprintf("INSERT INTO engagd_users (userId, url) VALUES('%s', '%s') ON DUPLICATE KEY UPDATE url = VALUES(url)",
		mysql_escape_string($userId),
		mysql_escape_string($url)
	);
	mysql_query($query, $link)
		or die("ERROR:Can't save user informations: " . mysql_error() . "\n");
}

function apml_request($url, $method='GET', $data=null) {
	global $config;
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; GobbleRSS/1.0; +http://gobblerss.pommepause.com/)");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
	if ($method == 'PUT') {
		$fh = fopen('php://memory', 'rw');
		fwrite($fh, $data);
		rewind($fh);
		curl_setopt($ch, CURLOPT_INFILE, $fh);
		curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data));
		curl_setopt($ch, CURLOPT_PUT, 4);
	} else if ($method != 'GET') {
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
	}
	curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
	$result = curl_exec($ch);
	if (curl_errno($ch) !== CURLE_OK) {
		if (curl_errno($ch) === CURLE_HTTP_RETURNED_ERROR) {
			$returnCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$result = "ERROR:HTTP:$returnCode:".curl_error($ch);
		} else {
			$result = 'ERROR:CURL:'.curl_errno($ch).':'.curl_error($ch);
		}
	}
	curl_close($ch);
	if (isset($fh)) {
		fclose($fh);
	}
	return $result;
}
?>